// src/utils.js
import { logInfo, logError, logWarn } from './logger.js';
import fetch from 'cross-fetch';
import CryptoJS from 'crypto-js';

export async function ensurePageOpen(context, url) {
    logInfo(`[ensurePageOpen] 尝试打开页面: ${url}`);
    if (!context) {
        logError('Browser context 未初始化，无法打开页面');
        throw new Error('Browser context 未初始化，无法打开页面');
    }
    let pages = context.pages && typeof context.pages === 'function' ? context.pages() : [];
    let currentPage = pages.find(p => p.url().includes(url));
    if (!currentPage) {
        currentPage = await context.newPage();
        await currentPage.goto(url);
        logInfo(`[ensurePageOpen] 新页面已打开: ${url}`);
    } else {
        await currentPage.bringToFront();
        logInfo(`[ensurePageOpen] 已切换到已打开页面: ${url}`);
    }
    return currentPage;
}

export function delay(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

/**
 * 安全地获取元素文本内容
 * @param {Object} element - Playwright元素对象
 * @param {*} defaultValue - 默认值
 * @returns {Promise<string>} 元素文本内容或默认值
 */
export async function safeGetText(element, defaultValue = '') {
    try {
        const text = await element.textContent();
        logInfo(`[safeGetText] 获取文本成功: ${text}`);
        return text;
    } catch (error) {
        logWarn(`[safeGetText] 获取元素文本失败: ${error.message}`);
        return defaultValue;
    }
}

/**
 * 安全地点击元素
 * @param {Object} element - Playwright元素对象
 * @param {number} timeout - 超时时间（毫秒）
 * @returns {Promise<boolean>} 是否点击成功
 */
export async function safeClick(element, timeout = 3000) {
    try {
        await element.click({ timeout });
        logInfo('[safeClick] 点击元素成功');
        return true;
    } catch (error) {
        logWarn(`[safeClick] 点击元素失败: ${error.message}`);
        return false;
    }
}

// 检查并关闭常见弹窗
export async function closePopups(page) {
    // 以常见关闭按钮为例，可根据实际页面调整选择器
    const selectors = [
        'svg[data-testid*="close"]',
        'svg[class*="close"]',
        'i[class*="close"]',
        'text="关闭"', // 新增文本选择器
        'button:has-text("关闭")' // 备用选择器
    ];
    let clicked = false;
    for (const selector of selectors) {
        const popup = await page.$(selector);
        if (popup) {
            const result = await popup.click({ timeout: 200 }).catch(() => false);
            if (result !== false) {
                clicked = true;
            }
        }
    }
    if (clicked) {
        // 如果有弹窗被关闭，递归再次尝试
        await closePopups(page);
    }
}

export async function cloud_cookie(host, uuid, password) {
  const url = host + '/get/' + uuid;
  const ret = await fetch(url);
  const json = await ret.json();
  let cookies = [];
  if (json && json.encrypted) {
    const { cookie_data, local_storage_data } = cookie_decrypt(uuid, json.encrypted, password);
    for (const key in cookie_data) {
      cookies = cookies.concat(cookie_data[key].map(item => {
        // Playwright 只接受 Strict|Lax|None
        if (!['Strict', 'Lax', 'None'].includes(item.sameSite)) item.sameSite = 'Lax';
        return item;
      }));
    }
  }
  return cookies;
}

function cookie_decrypt(uuid, encrypted, password) {
  const the_key = CryptoJS.MD5(uuid + '-' + password).toString().substring(0, 16);
  const decrypted = CryptoJS.AES.decrypt(encrypted, the_key).toString(CryptoJS.enc.Utf8);
  const parsed = JSON.parse(decrypted);
  return parsed;
}